package com.xlr.excel.util.excel;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: xlr
 * @Date: Created in 上午12:43 2019/3/1
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class SheetHandler extends DefaultHandler {

    private String filePath ;
    private Integer collSize;

    AtomicInteger atomicInteger = new AtomicInteger(  );

    private SharedStringsTable sst;
    private String lastContents;
    private boolean nextIsString;

    private int sheetIndex = -1;
    private List<String> rowlist = new ArrayList<String>();
    private int curRow = 0;
    private int curCol = 0;
    private int preCol = 0;
    private int titleRow = 0;
    private int rowsize = 0;

    /**
     *
     * @param filePath 文件路径
     * @param collSize 列数量
     */
    public SheetHandler(String filePath, Integer collSize){
        this.filePath = filePath;
        this.collSize = collSize;
    }
    //保存单个sheet数据
    private static List<List<String>> sheetData = new ArrayList<List<String>>();

    //保存所有sheet数据
    public static Map sheetMap = new HashMap();

    /**
     * 主要实现
     * @param sheetIndex
     * @param curRow
     * @param rowList
     */
    public void optRows(int sheetIndex, int curRow, List<String> rowList) {
        List temp = new ArrayList();
        temp.addAll(rowList);
        sheetData.add(temp);
    }

    public void process() throws InvalidFormatException,SAXException {
        OPCPackage pkg = OPCPackage.open(filePath);
        XSSFReader r = null;
        InputStream sheet = null;
        try {
            r = new XSSFReader(pkg);
            SharedStringsTable sst = r.getSharedStringsTable();

            XMLReader parser = fetchSheetParser(sst);
            Iterator<InputStream> sheets = r.getSheetsData();
            // sheets.hasNext()
            while (sheets.hasNext()) {
                curRow = 0;
                sheetIndex++;
                sheet = sheets.next();
                InputSource sheetSource = new InputSource(sheet);
                parser.parse(sheetSource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OpenXML4JException e) {
            e.printStackTrace();
        }finally {
            if (sheet != null) {
                try {
                    sheet.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    protected XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
        XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
        this.sst = sst;
        parser.setContentHandler(this);
        return parser;
    }
    @Override
    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        if (name.equals("c")) {
            String cellType = attributes.getValue("t");
            String rowStr = attributes.getValue("r");
            curCol = this.getRowIndex(rowStr);
            if (cellType != null && cellType.equals("s")) {
                nextIsString = true;
            } else {
                nextIsString = false;
            }
        }

        lastContents = "";
    }

    @Override
    public void endElement(String uri, String localName, String name) throws SAXException {
        if (nextIsString) {
            try {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
        if (name.equals("v")) {
            atomicInteger.getAndIncrement(  );
            int i1 = atomicInteger.get();
            // 11 是列数量
            if(  i1 < collSize){
                return;
            }
            String value = lastContents.trim();
            value = value.equals("") ? " " : value;
            int cols = curCol - preCol;
            if (cols > 1) {
                for (int i = 0; i < cols - 1; i++) {
                    rowlist.add(preCol, "");
                }
            }
            preCol = curCol;
            rowlist.add(curCol - 1, value);
        } else {
            if (name.equals("row")) {
                int tmpCols = rowlist.size();
                if (curRow > this.titleRow && tmpCols < this.rowsize) {
                    for (int i = 0; i < this.rowsize - tmpCols; i++) {
                        rowlist.add(rowlist.size(), "");
                    }
                }
                optRows(sheetIndex, curRow, rowlist);
                if (curRow == this.titleRow) {
                    this.rowsize = rowlist.size();
                }
                rowlist.clear();
                curRow++;
                curCol = 0;
                preCol = 0;
            }
        }
    }
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        lastContents += new String(ch, start, length);
    }

    protected int getRowIndex(String rowStr) {
        rowStr = rowStr.replaceAll("[^A-Z]", "");
        byte[] rowAbc = rowStr.getBytes();
        int len = rowAbc.length;
        float num = 0;
        for (int i = 0; i < len; i++) {
            num += (rowAbc[i] - 'A' + 1) * Math.pow(26, len - i - 1);
        }
        return (int) num;
    }

    protected int getTitleRow() {
        return titleRow;
    }

    protected void setTitleRow(int titleRow) {
        this.titleRow = titleRow;
    }
}
